package net.quanter.shield.springboot.interceptor;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import net.quanter.shield.mybatis.page.PageUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 分页拦截器，拦截web请求，直接把pageNum和pageSize放到前端中
 * Created by 2016/11/24.
 *
 * @author 王老实
 */
@Aspect
@Component
@Slf4j
public class PageInterceptor {

    @Pointcut("@annotation(net.quanter.shield.springboot.annotations.PageSupport)")
    private void pointcut() {
    }

    @Before(value = "pointcut()")
    public void before(JoinPoint joinPoint) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String sPageNum = request.getParameter(PageUtil.PAGE_NUM);
        String sPageSize = request.getParameter(PageUtil.PAGE_SIZE);
        if (sPageNum == null || sPageSize == null) {
            return;
        }
        boolean isPageNumValid = NumberUtil.isInteger(sPageNum);
        boolean isPageSizeValid = NumberUtil.isInteger(sPageSize);
        if (isPageNumValid) {
            log.error("pageNum[{}] is not a number", sPageNum);
        }
        if (isPageSizeValid) {
            log.error("pageSize[{}] is not a number", sPageSize);
        }
        Integer pageNum = isPageNumValid ? Integer.parseInt(sPageNum) : PageUtil.DEFAULT_PAGE_NUM;
        Integer pageSize = isPageSizeValid ? Integer.parseInt(sPageSize) : PageUtil.DEFAULT_PAGE_SIZE;
        PageUtil.set(pageNum, pageSize);
    }

    @After(value = "pointcut()")
    public void afterCompletion() throws Exception {
        PageUtil.remove();
    }

}

